//
//  UIViewController+ZKViewControllerTransition.m
//  朱凯的工具箱
//
//  Created by pro on 17/5/12.
//  Copyright © 2017年 zhukai. All rights reserved.
//

#import "UIViewController+transition.h"

#import <objc/runtime.h>

static const NSString *kAnimatorKey = @"kAnimatorKey";
static const NSString *kToIntercativeKey = @"kToIntercativeKey";
static const NSString *kBackIntercativeKey = @"kBackIntercativeKey";

@implementation UIViewController (ZKViewControllerTransition)

- (void)kz_presentViewController:(UIViewController *)vc
                        animator:(KZTransitionAnimator *)animator
                 backInteractive:(bool)backInteractive {

    if (vc == nil) return;
    
    // 设置动画控制器
    animator = animator ? animator : [[KZTransitionAnimator alloc] init];
    
    // 把vc的转场动画代理设置为动画控制器
    vc.transitioningDelegate = animator;
    // vc需要持有animator，否则无法给animator注册返回手势
    objc_setAssociatedObject(vc, &kAnimatorKey, animator, OBJC_ASSOCIATION_RETAIN);
    
    // 设置默认手势，edgePan，left
    backInteractive ? [vc kz_registerBackInteractive:nil gestureConfig:nil] : nil;
    
    // 调用跳转
    [self presentViewController:vc animated:YES completion:nil];
}


- (void)kz_registerToInteractive:(dispatch_block_t)operationBlock
                   gestureConfig:(void(^)(KZGestureConfigFetch fetch))gestureConfig {
    
    // TODO: 待完成
}

- (void)kz_registerBackInteractive:(dispatch_block_t)operationBlock
                     gestureConfig:(void(^)(KZGestureConfigFetch fetch))gestureConfig{

    // 检测两个block是否有值，若无，赋予默认操作
    __weak typeof(self) wself = self;
    dispatch_block_t tmp_operationBlock = operationBlock ? operationBlock : ^ {
        [wself dismissViewControllerAnimated:YES completion:nil];
    };
    void (^tmp_gestureConfig)(KZGestureConfigFetch fetch) = gestureConfig ? : ^(KZGestureConfigFetch fetchs) {
        
        if (fetchs) {
            fetchs(KZTransitionInteractiveGestureTypeEdgePan,
                   KZTransitionInteractiveDirectionLeft,
                   0);
        }
    };
    
    // 创建返回手势
    KZTransitionInteractiveConfig *backInteractive = [[KZTransitionInteractiveConfig alloc] initWithOperation:tmp_operationBlock gestureConfig:tmp_gestureConfig];
    
    // 把手势添加在view上
    [backInteractive addGestureToView:wself.view];
    
    // 设置动画控制器的手势适配器属性，作为UIViewControllerTransitionDelegate的手势方法回调
    KZTransitionAnimator *animator = objc_getAssociatedObject(wself, &kAnimatorKey);
    if (animator) {
        [animator setValue:backInteractive forKey:@"backInteractive"];
    }
}



@end
